/**
 * Created by ${PRODUCT_NAME}.
 * User: skylerparr
 * Date: 1/2/11
 * Time: 1:32 PM
 * To change this template use File | Settings | File Templates.
 */
package com.thoughtorigin.meta {
import com.thoughtorigin.events.ComponentDrawEvent;
import com.thoughtorigin.meta.MetaType;
import com.thoughtorigin.module.ModuleLoader;
import com.thoughtorigin.reflect.MetaDataItem;

import com.thoughtorigin.util.Instantiator;

import flash.display.DisplayObject;
import flash.display.DisplayObject;
import flash.system.ApplicationDomain;
import flash.utils.describeType;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;

public class View implements MetaType {

    private var _instantiator:Instantiator;
    private var _metaOperator:MetaOperator;

    public function View() {
    }

    public function decorate(object:Object, metadata:MetaDataItem, callback:Function):void {
        var componentName: String = getQualifiedClassName(object) + "View";
        var view: DisplayObject = DisplayObject(_instantiator.createByClassName(componentName, []));
        _metaOperator.injectObject(view, function(): void {
            if(view is DrawingComponent) {
                DrawingComponent(view).addEventListener(ComponentDrawEvent.DRAW_COMPLETE, function(e: ComponentDrawEvent): void {
                    DrawingComponent(view).removeEventListener(ComponentDrawEvent.DRAW_COMPLETE, arguments.callee);
                    viewComplete(callback, object, metadata, view);
                });
                DrawingComponent(view).draw();
                return;
            }
            viewComplete(callback, object, metadata, view);
        });
    }

    private function viewComplete(callback: Function, object: Object, metadata: MetaDataItem, view: DisplayObject): void {
        object[metadata.decoratedPropertyName] = view;
        callback.call(this);
    }

    public function preprocess(clazz:Class, metadata:MetaDataItem):void {
    }

    public function get priority():int {
        return 0;
    }

    public function dispose(... args):void {
    }

    [Inject]
    public function set metaOperator(value: MetaOperator): void {
        _metaOperator = value;
    }

    [Inject]
    public function set instantiator(value: Instantiator): void {
        _instantiator = value;
    }

}
}
